#java current date Using java.util.Date instance
Explore tagged Tumblr posts
fromdevcom Ā· 1 month ago
Text
Date manipulation is required in everyday Java programming. Creating a date instance for a past or future date is required at many places where we are trying to have a date range. I have seen many developers keep searching on google about "how to add or subtract days in java.util.Date". or "how to calculate 7 days date past or future from present date in core java" My previous post about date utility methods used setTime() method of Date object for getting the back date. After doing some more reading I realized that this can be done in a much easier manner by using java.util.Calendar.add() method. Good thing about this method is the static final constants provided by java.util.Calendar class itself. This gives more flexibility in manipulating the date with all levels of constants. Calendar.SECOND Calendar.MINUTE Calendar.HOUR Calendar.DATE Calendar.MONTH Calendar.YEAR Below are the example methods which uses Calendar.add method with these constants. This demonstrates how we can get a past of future date for any time we are looking for(Seconds, minutes,hours, days,months or years) /** * Get the date java.util.Date object for days before current date * * @param days * @return */ public static Date getDateBeforeDays(int days) Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -days); // -days return cal.getTime(); /** * Get the date java.util.Date object for days after current date * * @param days * @return */ public static Date getDateAfterDays(int days) Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, days); // +days return cal.getTime(); /** * Get the date java.util.Date object for years after current date * * @param years * @return */ public static Date getDateAfterYears(int years) Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, years); // +years return cal.getTime(); /** * Get the date java.util.Date object for years before current date * * @param years * @return */ public static Date getDateBeforeYears(int years) Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -years); // -years return cal.getTime(); /** * Get the date java.util.Date object for months after current date * * @param months * @return */ public static Date getDateAfterMonths(int months) Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, months); // +months return cal.getTime(); /** * Get the date java.util.Date object for months before current date * * @param months * @return */ public static Date getDateBeforeMonths(int months) Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -months); // -months return cal.getTime(); /** * Get the date java.util.Date object for hours before current date * * @param hours * @return */ public static Date getDateBeforeHours(int hours) Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -hours); // -hours return cal.getTime(); /** * Get the date java.util.Date object for hours after current date * * @param hours * @return */ public static Date getDateAfterHours(int hours) Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, hours); // +hours return cal.getTime(); /** * Get the date java.util.Date object for minutes before current date * * @param minutes * @return */ public static Date getDateBeforeMinutes(int minutes) Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, -minutes); // -minutes return cal.getTime(); /** * Get the date java.util.Date object for minutes after current date * * @param minutes * @return */ public static Date getDateAfterMinutes(int minutes) Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, minutes); // +minutes return cal.getTime(); /** * Get the date java.util.Date object for seconds before current date * * @param seconds * @return */ public static Date getDateBeforeSeconds(int seconds) Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, -seconds); // -seconds return cal.getTime(); /** * Get the date java.util.Date object for seconds after current date
* * @param seconds * @return */ public static Date getDateAfterSeconds(int seconds) Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, seconds); // +seconds return cal.getTime(); The java.util.Date class has been deprecated since Java 1.1 and has been replaced by the java.time package since Java 8. The java.time package introduced a new set of classes that provide more functionality and better handling of date and time operations, such as LocalDate, LocalTime, and LocalDateTime. It is recommended to use these new classes instead of the deprecated java.util.Date class for date and time operations. Here is another example to get instance of specific date in java. How to get Java Date of past?, How to get Java Date of future?, How to get Java Date after days, Java Date before days, Java Date after months, Java date after years,Java Date before months, Java date before years, Java Date future, getting of future date by using number of days and format java, getting of past date by using number of days and format java, How to get Java Time of past?, How to get Java Time of future?, How to get Java Time after days, Java Time before days, Java Time after months, Java date after years,Java Time before months, Java date before years, Java Time future, getting of future date by using number of days and format java, getting of past date by using number of days and format java, Java previous Date, Java next date, How to get Java Time of previous?, How to get Java Time of next? Java Time next, getting of next date by using number of days and format java, getting of previous date by using number of days and format java, How to get Java Date of previous?, How to get Java Date of next? Java Date next, calendar getinstance, Java date utilities, Java date Utility, Java date Util, display a future date in java, java date future, java future date, java date util functions, date function java, util function java
0 notes
techandguru-blog Ā· 6 years ago
Link
Almost everything is driven by date and time in today's world. People started equating time with money. So computer and programming languages have a way to date time measure implementation. In this post, I will get you through date and time in java. We will see the date and time in java in detail with example.Ā 
Tumblr media
Java Date
Java hasĀ DateĀ class implementation inĀ java.utilĀ package. This class has the current date and time implementation too. Date class has two constructors as shown below:
-Ā Date(): this constructor initializes the class with the current date and time.
-Ā Date(long milliseconds): this constructor takes millisecond of the date since midnight 1 Jan 1970 and initializes the date and time accordingly.
Like other java class, Date classĀ also has certain methods. Commonly used Date methods are listed below:
Method Signature Method Description boolean after(Date date) returns true if invoking date object contains a dateĀ that is later than the date inĀ the argument date object boolean before(Date date) return true if invoking date object contains a date that is earlier than the date inĀ the argument date object Object clone( ) create the duplicate of the invoking date object. It creates new references. int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. int compareTo(Object obj) it is same as of compareTo(Date date) provided argument type is of Date otherwise it throws ClassCastException. boolean equals(Object date) return true if invoking date object and argument date object contains same date and time otherwise false. [argument should be of type Date] long getTime( ) returns the milliseconds since midnight of 1 Jan 1970 for the invoking object int hashCode( ) returns hashcode of invoking the object void setTime(long time) initializes the date and time of the invoking object with the argument. String toString( ) Ā Converts the invoking Date object into a string and returns the result.Ā 
GETTING CURRENT DATE AND TIME IN JAVA:
In two ways you can have current date and time using Date class
- by retrieving millisecond of the Date object
- by retrieving String of Date object
e.g.Ā  import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate an object date of Date class Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); // display millisecond of date using getTime() System.out.println(date.getTime()); }Ā }
COMPARING DATES IN JAVA
Date and time in java can be compared using three approaches
- getting milliseconds of the Date objects and comparing them
- using compareTo(Date date) method of the Date class
- using before(Date date), after(Date date) and equal(Date date) method of the Date class.
Date and Time formatting using SimpleDateFormat:
SimpleDateFormat class is the concrete way to format date. It has a locale-sensitive parsing. It allows formatting date in any user-friendly way.
import java.util.*; import java.text.*; public class DateFormatExample { public static void main(String args[]) { Date dNow = new Date(); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); } }
The output of the above program is
Current Date: Sun 20019.07.18 at 04:14:09 PM PDT
SimpleDateFormat FORMATTING CODES:
ASCII letters reserved as pattern letter are as follows:
ASCII LETTER Description Example G Era designator AD y Year in four digits 2019 M Month in year July or 07 d Day in month 10 h Hour in A.M./P.M. (1~12) 12 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 1564725881 E Day in week Tuesday D Day in year 365 F Day of week in the month 2 (second Wed. in July) w Week in year 40 W Week in month 1 a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. (0~11) 10 z Time zone Eastern Standard Time ' Escape for text Delimiter " Single quote `
FORMATTING Date object USING printf()
Note: to avoid passing argument multiple times while formatting using printf, better use "%1$s" where letter after % indicates the index of the argument to be used so to specify the index in printf, the index must follow % and then terminated by $.
- to useĀ  the argument in the preceding formatting clause, use < flag.
e.g.
import java.util.Date; public class DateFormattingPrintfExmple { public static void main(String args[]) { // Instantiate a date object of class Date Date date = new Date(); // display formatted time and date using printf System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); } }
PARSING STRING IN DATE
SimpleDateFormat class has method parse() which can parse the string according to the format stored in the SimpleDateFormat.
import java.util.*; import java.text.*; public class ParsingStringIntoDateExample { public static void main(String args[]) { SimpleDateFormat sft = new SimpleDateFormat ("yyyy-MM-dd"); //initialize formatter with format String input = "2019-07-11"; System.out.print(input + " Parses as "); Date t; try { t = sft.parse(input); System.out.println(t); } catch (ParseException e) { System.out.println("Unparseable using " + ft); } } }
- lapsed time can be measured by taking the difference of milliseconds of start time and end time.
GregorianCalendar Overview
Apart from using Date() for date and time, GregorianCalendar instance can be used to create the calendar instance. It has various constructors to initialized the Calendar instance. By default, the constructor returns instance initialized with current time and time zone of the user. GregorianCalendar represents two eras AD and BC
Here is the constructor list of GregorianCalendar
Constructor Ā Description GregorianCalendar()Ā  Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale. GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default locale. GregorianCalendar(TimeZone zone, Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.
For more details on GregorianCalendar, please check Oracle Java documentation.
You are at the end of the article, Hope you enjoyed it. please share and subscribe for latest articles on technology.
You may like Understanding Java From Scratch and Java Interview MCQ
0 notes